package org.example.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.example.entity.Category;
import org.example.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

@RestController
@RequestMapping("/category")
@CrossOrigin(origins = "*")
public class CategoryController {

    @Autowired
    private CategoryMapper categoryMapper;

    // List categories; optional filter by type
    @GetMapping("/list")
    public Map<String, Object> getCategoryList(@RequestParam(required = false) Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        if (type != null) {
            wrapper.eq(Category::getType, type);
        }
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categories = categoryMapper.selectList(wrapper);

        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "查询成功");
        result.put("data", categories);
        return result;
    }

    // Category pagination
    @GetMapping("/page")
    public Map<String, Object> getCategoryPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name) {

        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            wrapper.like(Category::getName, name);
        }
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        categoryMapper.selectPage(pageInfo, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("records", pageInfo.getRecords());
        data.put("total", pageInfo.getTotal());
        data.put("current", pageInfo.getCurrent());
        data.put("size", pageInfo.getSize());

        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "查询成功");
        result.put("data", data);
        return result;
    }

    // Create category. type: 1=dish, 2=setmeal
    @PostMapping
    public Map<String, Object> addCategory(@RequestBody Category category) {
        LocalDateTime now = LocalDateTime.now();
        category.setCreateTime(now);
        category.setUpdateTime(now);
        // 临时写死为演示用户ID，后续可从登录上下文获取
        if (category.getCreateUser() == null) {
            category.setCreateUser(1L);
        }
        if (category.getUpdateUser() == null) {
            category.setUpdateUser(1L);
        }
        categoryMapper.insert(category);

        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "添加成功");
        return result;
    }

    // Get one category by id
    @GetMapping("/{id}")
    public Map<String, Object> queryCategoryById(@PathVariable Long id) {
        Category category = categoryMapper.selectById(id);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "查询成功");
        result.put("data", category);
        return result;
    }

    // Update category (only name, sort) to avoid null-overwrite on other fields like type
    @PutMapping
    public Map<String, Object> updateCategory(@RequestBody Category category) {
        Map<String, Object> result = new HashMap<>();
        if (category.getId() == null) {
            result.put("code", 0);
            result.put("msg", "ID不能为空");
            return result;
        }

        Category db = categoryMapper.selectById(category.getId());
        if (db == null) {
            result.put("code", 0);
            result.put("msg", "分类不存在");
            return result;
        }

        db.setName(category.getName());
        db.setSort(category.getSort());
        db.setUpdateTime(LocalDateTime.now());
        if (db.getUpdateUser() == null) {
            db.setUpdateUser(1L);
        }
        int rows = categoryMapper.updateById(db);
        if (rows <= 0) {
            result.put("code", 0);
            result.put("msg", "修改失败");
            return result;
        }

        result.put("code", 1);
        result.put("msg", "修改成功");
        return result;
    }

    // Delete category by id(s), supports single id or comma-separated ids
    @DeleteMapping
    public Map<String, Object> deleteCategory(@RequestParam String ids) {
        int affected = 0;
        if (ids.contains(",")) {
            for (String idStr : ids.split(",")) {
                if (idStr == null || idStr.isEmpty()) continue;
                affected += categoryMapper.deleteById(Long.valueOf(idStr));
            }
        } else {
            affected = categoryMapper.deleteById(Long.valueOf(ids));
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", affected > 0 ? 1 : 0);
        result.put("msg", affected > 0 ? "删除成功" : "未删除任何记录");
        return result;
    }
}

